package org.abratuhi.kvngroupware.jokemanager.widget;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.io.File;
import java.util.EventObject;
import java.util.Properties;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JScrollPane;
import javax.swing.JSpinner;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SpinnerListModel;
import javax.swing.event.CellEditorListener;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableCellRenderer;

import org.abratuhi.kvngroupware.KVNGroupwareClientAction;
import org.abratuhi.kvngroupware.jokemanager.manager.JokeManager;
import org.abratuhi.kvngroupware.jokemanager.model.Joke;
import org.abratuhi.kvngroupware.login.manager.LoginManager;
import org.abratuhi.kvngroupware.network.Message;
import org.abratuhi.kvngroupware.network.MessageSender;
import org.abratuhi.kvngroupware.widget.AbstractWorkWidget;
import org.jdom.Element;

@SuppressWarnings("serial")
public class GuiJokeManager extends AbstractWorkWidget{
	LoginManager loginmanager;
	JokeManager jokemanager;
	
	String[] tableColumns;
	JokeManagerTableModel tableModel;
	DefaultTableModel defaultModel;
	JTable table;
	
	public GuiJokeManager(String frameid, String frametitle, MessageSender sender, Properties locale, 
			LoginManager loginmanager, JokeManager jokemanager){
		super(frameid, frametitle, sender, locale);
		this.loginmanager = loginmanager;
		this.jokemanager = jokemanager;
		
		this.tableColumns = locale.getProperty("jokesmanager.columns").split(",");
		this.defaultModel = new DefaultTableModel(tableColumns, 0);
		this.tableModel = new JokeManagerTableModel();
		//this.table = new JTable(this.tableModel);
		this.table = new JTable(this.defaultModel);
		
		//for(int i=0; i<tableColumns.length; i++) defaultModel.addColumn(tableColumns[i]);
		//for(int i=0; i<tableColumns.length; i++) table.addColumn(new TableColumn());
		//for(int i=0; i<tableColumns.length; i++) table.getColumnModel().getColumn(i).setHeaderValue(tableColumns[i]);
		
		//this.tableModel.removeTableModelListener(table);
		
		table.getColumnModel().getColumn(0).setCellEditor(new TextFieldEditor());
		table.getColumnModel().getColumn(1).setCellEditor(new TextAreaEditor());
		table.getColumnModel().getColumn(2).setCellEditor(new SpinnerEditor());
		table.getColumnModel().getColumn(3).setCellEditor(new ButtonEditor());
		table.getColumnModel().getColumn(4).setCellEditor(new ButtonEditor());
		table.getColumnModel().getColumn(5).setCellEditor(new ButtonEditor());
		
		table.getColumnModel().getColumn(0).setCellRenderer(new TextFieldRenderer());
		table.getColumnModel().getColumn(1).setCellRenderer(new TextAreaRenderer());
		table.getColumnModel().getColumn(2).setCellRenderer(new SpinnerRenderer());
		table.getColumnModel().getColumn(3).setCellRenderer(new ButtonRenderer());
		table.getColumnModel().getColumn(4).setCellRenderer(new ButtonRenderer());
		table.getColumnModel().getColumn(5).setCellRenderer(new ButtonRenderer());
		
		table.getColumnModel().getColumn(0).setMaxWidth(40);
		//table.getColumnModel().getColumn(1).setMaxWidth(20);
		table.getColumnModel().getColumn(2).setMaxWidth(40);
		table.getColumnModel().getColumn(3).setMaxWidth(40);
		table.getColumnModel().getColumn(4).setMaxWidth(40);
		table.getColumnModel().getColumn(5).setMaxWidth(40);
		
		for(int i=0;i<tableColumns.length; i++) table.getColumnModel().getColumn(i).setHeaderValue(tableColumns[i]);
		
		setLayout(new BorderLayout());
		setPreferredSize(new Dimension(500, 400));
		add(new JScrollPane(table), BorderLayout.CENTER);
	}
	
	public void onFrameClose(){
		
	}
	
	public void paint(Graphics g){
		super.paint(g);
		//tableModel.data = kvnclient.getJokesAsTableData();
		//defaultModel = new DefaultTableModel(kvnclient.getJokesAsTableData(), tableColumns);
		String[][] jokesdata = getJokesAsTableData();
		defaultModel.setRowCount(0);
		for(int i=0; i<jokesdata.length; i++) defaultModel.addRow(jokesdata[i]);
	}
	
	public String[][] getJokesAsTableData(){
		String[][] data = new String[jokemanager.size()][locale.getProperty("jokesmanager.columns").split(",").length];
		String[] jokeIds = jokemanager.getkeys();
		for(int i=0; i<jokeIds.length; i++){
			Joke joke = jokemanager.get(jokeIds[i]);
			data[i][0] = joke.getId();
			data[i][1] = joke.getText();
			data[i][2] = joke.getRating();
			data[i][3] = "n" + "," + joke.getId();
			data[i][4] = "u" + "," + joke.getId();
			data[i][5] = "d" + "," + joke.getId();
		}
		return data;
	}
	
	public class JokeManagerTableModel extends AbstractTableModel{
		public String[][] data = new String[0][tableColumns.length];
		String[] columns = tableColumns;

		@Override
		public int getColumnCount() {
			return columns.length;
		}

		@Override
		public int getRowCount() {
			return data.length;
		}

		@Override
		public Object getValueAt(int rowIndex, int columnIndex) {
			return data[rowIndex][columnIndex];
		}
		
		public boolean isCellEditable(int rowIndex, int columnIndex){
			return true;
		}
	}
	
	
	class TextFieldRenderer implements TableCellRenderer{
		
		JTextField textfield = new JTextField();

		@Override
		public Component getTableCellRendererComponent(JTable table,
				Object value, boolean isSelected, boolean hasFocus, int row,
				int column) {
			textfield.setText((String) value);
			return textfield;
		}
		
	}
	
	class TextFieldEditor extends TextFieldRenderer implements TableCellEditor{

		@Override
		public Component getTableCellEditorComponent(JTable table,
				Object value, boolean isSelected, int row, int column) {
			return getTableCellRendererComponent(table, value, isSelected, true, row, column);
		}

		@Override
		public void addCellEditorListener(CellEditorListener l) {
			listenerList.add(CellEditorListener.class, l);
		}

		@Override
		public void cancelCellEditing() {
		}

		@Override
		public Object getCellEditorValue() {
			return textfield.getText();
		}

		@Override
		public boolean isCellEditable(EventObject anEvent) {
			return false;
		}

		@Override
		public void removeCellEditorListener(CellEditorListener l) {
			listenerList.remove(CellEditorListener.class, l);
		}

		@Override
		public boolean shouldSelectCell(EventObject anEvent) {
			return true;
		}

		@Override
		public boolean stopCellEditing() {
			return true;
		}
	}
	
	public class TextAreaRenderer implements TableCellRenderer{
		
		public JTextArea textarea = new JTextArea();
		JScrollPane scrollpane = new JScrollPane(textarea);

		@Override
		public Component getTableCellRendererComponent(JTable table,
				Object value, boolean isSelected, boolean hasFocus, int row,
				int column) {
			textarea.setText((String) value);
			textarea.setWrapStyleWord(true);
			textarea.setLineWrap(true);
			textarea.setColumns(50);
			textarea.setRows(2);
			scrollpane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
			return scrollpane;
			//return textarea;
		}
		
	}
	
	class TextAreaEditor extends TextAreaRenderer implements TableCellEditor{
		@Override
		public Component getTableCellEditorComponent(JTable table,
				Object value, boolean isSelected, int row, int column) {
			return getTableCellRendererComponent(table, value, isSelected, true, row, column);
		}
		@Override
		public void addCellEditorListener(CellEditorListener l) {
			listenerList.add(CellEditorListener.class, l);
		}
		@Override
		public void cancelCellEditing() {}
		@Override
		public Object getCellEditorValue() {
			return textarea.getText();
		}
		@Override
		public boolean isCellEditable(EventObject anEvent) {
			return true;
		}
		@Override
		public void removeCellEditorListener(CellEditorListener l) {
			listenerList.remove(CellEditorListener.class, l);
		}
		@Override
		public boolean shouldSelectCell(EventObject anEvent) {
			return true;
		}
		@Override
		public boolean stopCellEditing() {
			return true;
		}
	}
	
	class ButtonRenderer implements TableCellRenderer{
		ImageIcon icon1 = new ImageIcon("images"+File.separator+"New24.gif");
		ImageIcon icon2 = new ImageIcon("images"+File.separator+"Save24.gif");
		ImageIcon icon3 = new ImageIcon("images"+File.separator+"Delete24.gif");
		
		JButton button = new JButton();

		@Override
		public Component getTableCellRendererComponent(JTable table,
				Object value, boolean isSelected, boolean hasFocus, int row,
				int column) {
			String[] params = ((String) value).split(",");
			
			String text = params[0];
			String id = params[1];
			
			if(text.equals("n")){
				button.setAction(new NewAction("", icon1, null, null, id));
			}
			else if(text.equals("u")){
				button.setAction(new UpdateAction("", icon2, null, null, id));
			}
			else if(text.equals("d")){
				button.setIcon(icon3);
				button.setAction(new DeleteAction("", icon3, null, null, id));
			}
			
			return button;
		}
	}
	
	class ButtonEditor extends ButtonRenderer implements TableCellEditor{
		@Override
		public Component getTableCellEditorComponent(JTable table,
				Object value, boolean isSelected, int row, int column) {
			return getTableCellRendererComponent(table, value, isSelected, true, row, column);
		}
		@Override
		public void addCellEditorListener(CellEditorListener l) {
			listenerList.add(CellEditorListener.class, l);
		}
		@Override
		public void cancelCellEditing() {}

		@Override
		public Object getCellEditorValue() {
			return button.getText();
		}
		@Override
		public boolean isCellEditable(EventObject anEvent) {
			return true;
		}
		@Override
		public void removeCellEditorListener(CellEditorListener l) {
			listenerList.remove(CellEditorListener.class, l);
		}
		@Override
		public boolean shouldSelectCell(EventObject anEvent) {
			return true;
		}
		@Override
		public boolean stopCellEditing() {
			return true;
		}
	}
	
	class SpinnerRenderer implements TableCellRenderer{
		JSpinner spinner = new JSpinner(new SpinnerListModel(Joke.RATINGS));

		@Override
		public Component getTableCellRendererComponent(JTable table,
				Object value, boolean isSelected, boolean hasFocus, int row,
				int column) {
			spinner.setValue(value);
			return spinner;
		}
	}
	
	class SpinnerEditor extends SpinnerRenderer implements TableCellEditor{
		@Override
		public Component getTableCellEditorComponent(JTable table,
				Object value, boolean isSelected, int row, int column) {
			return getTableCellRendererComponent(table, value, isSelected, true, row, column);
		}
		@Override
		public void addCellEditorListener(CellEditorListener l) {
			listenerList.add(CellEditorListener.class, l);
		}
		@Override
		public void cancelCellEditing() {}
		@Override
		public Object getCellEditorValue() {
			return spinner.getValue();
		}
		@Override
		public boolean isCellEditable(EventObject anEvent) {
			return true;
		}
		@Override
		public void removeCellEditorListener(CellEditorListener l) {
			listenerList.remove(CellEditorListener.class, l);
		}
		@Override
		public boolean shouldSelectCell(EventObject anEvent) {
			return true;
		}
		@Override
		public boolean stopCellEditing() {
			return true;
		}
	}
	
	class NewAction extends KVNGroupwareClientAction{
		String id;
		public NewAction(String text, ImageIcon icon, String desc,
				Integer mnemonic, String id) {
			super(text, icon, desc, mnemonic);
			this.id = id;
		}
		@Override
		public void actionPerformed(ActionEvent e) {
			Joke newjoke = new Joke("", loginmanager.getUser().getId(), loginmanager.getTeam().getId(), Joke.RATINGS[0]);
			
			String[] attrNames = new String[]{"type", "action", "teamId", "userId", "jokeId"};
			String[] attrValues= new String[]{"joke", "create", newjoke.getTeamId(), newjoke.getAuthorId(), newjoke.getId()};
			String text = new String();
			Element[] content = new Element[]{newjoke.toElement()};
			
			Message message = sender.createMessage(attrNames, attrValues, text, content);
			sender.sendMessage(message);
		}
		
	}
	class UpdateAction extends KVNGroupwareClientAction{
		String id;
		public UpdateAction(String text, ImageIcon icon, String desc,
				Integer mnemonic, String id) {
			super(text, icon, desc, mnemonic);
			this.id = id;
		}
		@Override
		public void actionPerformed(ActionEvent e) {
			Joke selectedJoke = jokemanager.get(id);
			String[] attrNames = new String[]{"type", "action", "teamId", "userId", "jokeId"};
			String[] attrValues= new String[]{"joke", "update", selectedJoke.getTeamId(), selectedJoke.getAuthorId(), selectedJoke.getId()};
			String text = new String();
			Element[] content = new Element[]{selectedJoke.toElement()};
			
			Message message = sender.createMessage(attrNames, attrValues, text, content);
			sender.sendMessage(message);
		}
		
	}
	class DeleteAction extends KVNGroupwareClientAction{
		String id;
		public DeleteAction(String text, ImageIcon icon, String desc,
				Integer mnemonic, String id) {
			super(text, icon, desc, mnemonic);
			this.id = id;
		}
		@Override
		public void actionPerformed(ActionEvent e) {
			Joke selectedJoke = jokemanager.get(id);
			String[] attrNames = new String[]{"type", "action", "teamId", "userId", "jokeId"};
			String[] attrValues= new String[]{"joke", "delete", selectedJoke.getTeamId(), selectedJoke.getAuthorId(), selectedJoke.getId()};
			String text = new String();
			Element[] content = new Element[]{selectedJoke.toElement()};
			
			Message message = sender.createMessage(attrNames, attrValues, text, content);
			sender.sendMessage(message);
		}
		
	}
}
